//
//  LYYSearchViewController.m
//  TravelDiary
//
//  Created by lanou3g on 15/11/16.
//  Copyright © 2015年 YDB MAC. All rights reserved.
//

#import "LYYSearchViewController.h"
#import "LYYSearchBar.h"
#import "LYYSearchCollectionViewCell.h"
#import <AFNetworking/AFNetworking.h>
#import "SearchCell.h"
#import "CityButtonCell.h"
#import "CityBDetailViewController.h"

#define kSearchUrl  @"http://app.quanjingke.com/api.php?appKey=ad36b8ed4ee6ee55faf7f00adf5d0dab&op=api_search&keyword=%@&userId=505425"


@interface LYYSearchViewController ()<UITextFieldDelegate,UITableViewDataSource,UITableViewDelegate>


@property (strong, nonatomic) IBOutlet UITableView *tableView;



@property (nonatomic, strong) NSMutableArray *dataArray;

@property (nonatomic, copy) NSString *cityName;

@property (nonatomic, strong) UIView *fanprogressView;

@end

@implementation LYYSearchViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    
    self.view.backgroundColor = [UIColor whiteColor];
    
    if (self.cityName == nil || [self.cityName isEqualToString:@""]) {
        
    }else{
        [_searchBar resignFirstResponder];
    }
    //导航栏
    [self loadNav];
    [self loadTableView];
    
    [self loadData];
    //添加通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(citychange:) name:@"location" object:self.cityName];
}
- (void)loadTableView{
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    
    if (self.cityName == nil) {
        
        [self.tableView registerNib:[UINib nibWithNibName:@"SearchCell" bundle:nil] forCellReuseIdentifier:@"SearchCell"];
    }else{
        [self.tableView registerNib:[UINib nibWithNibName:@"CityButtonCell" bundle:nil] forCellReuseIdentifier:@"CityButtonCell"];
    }
    self.tableView.tableFooterView = [[UIView alloc]init];
}
-(void)citychange:(NSNotification *)center
{
    self.cityName = center.object;
    
    [self loadTableView];
    [self loadData];
    [_searchBar resignFirstResponder];
}

#pragma mark-数据解析
- (void)loadData{
    if ([self.cityName isEqualToString:@""] || self.cityName == nil) {
        
    }else{
        _dataArray =[[NSMutableArray alloc]init];
        AFHTTPSessionManager *mgr = [AFHTTPSessionManager manager];
        mgr.responseSerializer = [AFHTTPResponseSerializer serializer];
        [mgr GET:[NSString stringWithFormat:kSearchUrl,[self.cityName stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]] parameters:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nonnull responseObject) {
            if ([responseObject isKindOfClass:[NSData class]]) {
                [_dataArray removeAllObjects];
                NSArray *array=[NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
                if (array.count == 0) {
                    
                    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"抱歉！没有您想要的信息！" preferredStyle:UIAlertControllerStyleAlert];
                   
                    UIAlertAction *action = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
                        [self.navigationController popToRootViewControllerAnimated:YES];
                        
                    }];
                    [alert addAction:action];
                    [self presentViewController:alert animated:YES completion:nil];
                    
                }
                [_dataArray addObjectsFromArray:array];
                [_tableView reloadData];
            }
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        }];
    }
    
    

}
#pragma mark --tableView

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (self.cityName == nil) {
        return 2;
    }else{
        return _dataArray.count;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (self.cityName ==nil) {
        return 120;
    }else{
       return 100;
    }
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (self.cityName == nil) {
        static NSString *CellIdentifier = @"SearchCell";
        
        SearchCell *cell= [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
        if (indexPath.row == 0) {
            cell.titleLabel.text = @"热搜省份:";
            cell.flag = 0;
            
        }else if(indexPath.row == 1){
            cell.titleLabel.text = @"热搜景区:";
            cell.flag = 1;
        }
        return cell;
    }else{
        static NSString *cellButtonIdentifier = @"CityButtonCell";
    
        
        CityButtonCell *buttonCell = [tableView dequeueReusableCellWithIdentifier:cellButtonIdentifier];
        
        NSDictionary *dict=[_dataArray objectAtIndex:indexPath.row];
        
        buttonCell.cityLabel.text = [dict objectForKey:@"address"];
        buttonCell.cityLabel.textColor = [UIColor purpleColor];
        buttonCell.addressLabel.text = [dict objectForKey:@"title"];
        buttonCell.addressLabel.textColor=[UIColor magentaColor];

        return buttonCell;
        
        
    }
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
  
    if (self.cityName == nil || [self.cityName isEqualToString:@""]) {
       
    }else{
        CityBDetailViewController *cityVc = [[CityBDetailViewController alloc]init];

         cityVc.detailDict=[_dataArray objectAtIndex:indexPath.row];
        
        [self.navigationController pushViewController:cityVc animated:YES];
    }
    
}


- (void)loadNav{
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemReply target:self action:@selector(leftBarButtonItemClick:)];
    //中间按钮
    _searchBar = [LYYSearchBar searchBar];
    _searchBar.delegate = self;
    //当点击UITextField的时候不要弹出键盘
//    _searchBar.inputView = [[UIView alloc]initWithFrame:CGRectZero];
    //尺寸
    _searchBar.frame = CGRectMake(0, 0, 300, 30);
    //设置中间的标题内容
    self.navigationItem.titleView = _searchBar;
   [_searchBar becomeFirstResponder];
    
}
- (void)leftBarButtonItemClick:(UIBarButtonItem *)bar{
    [self.navigationController popToRootViewControllerAnimated:YES];
    
}
#pragma mark -键盘回收
- (BOOL)textFieldShouldReturn:(UITextField *)textField{
    
    [textField resignFirstResponder];
    self.cityName = textField.text;
    
    [self loadTableView];
    [self loadData];
    
    return YES;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
